package main

import (
	"bytes"
	context2 "context"
	"encoding/json"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"log"
	"net"
	"testRpc/zybRpcProto"
	"time"
)

const (
	Address = "0.0.0.0:7788"
)

type msgHandle struct {
}

func (m msgHandle) SendOrder(ctx context2.Context, req *zybRpcProto.OrderReq) (*zybRpcProto.OrderRsp, error) {
	log.Println("------recv -----")
	printJson(req)
	rsp := &zybRpcProto.OrderRsp{
		RetCode: 0,
		AccountId: req.AccountId,
		OrderId: uint64(time.Now().Unix()),
	}

	return rsp, nil
}

func (m msgHandle) QryGoods(ctx context2.Context, req *zybRpcProto.GoodsReq) (*zybRpcProto.GoodsRsp, error) {
	log.Println("------recv -----")
	printJson(req)
	rsp := &zybRpcProto.GoodsRsp{
		GoodsCode: "GC2012",
		GoodsId: 96,
		GoodsName: "纽约期金",
	}

	return rsp, nil
}

func main() {
	fmt.Printf("start Rpc server[%s]", Address)
	if l, err := net.Listen("tcp", Address); err == nil {
		var h msgHandle
		s := grpc.NewServer()
		zybRpcProto.RegisterZybRpcServer(s, h)
		reflection.Register(s)
		fmt.Println("listen, ", Address)
		if err := s.Serve(l); err != nil {
			fmt.Println(err)
			return
		}
	} else {
		fmt.Println(err)
		return
	}

	time.Sleep(time.Minute * 10000)
}

func printJson(v interface{}) {
	if buf, err := json.Marshal(v); err == nil {
		var out bytes.Buffer
		if err := json.Indent(&out, buf, "", " "); err == nil {
			log.Println(out.String())
		}else {
			log.Println(err)
		}
	}else{
		log.Println(err)
	}
}
